import { s_getcommontableinfo, s_getSelectData, s_getStockInfo, s_getTableInfo, s_getTableInfoDetail, s_produce_updateInfo, s_stockIn, s_stockOut, status2text } from "@/services/basis";
import { YahooFilled } from "@ant-design/icons";
import { ActionType, EditableFormInstance, EditableProTable, heILIntl, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormDateRangePicker, ProFormDigit, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProTable } from "@ant-design/pro-components";
import { Button, Col, message, Modal, Row, Space ,Image} from "antd";
import { random } from "lodash";
import moment from "moment";
import { Item } from "rc-menu";
 
import { useEffect, useRef, useState } from "react";
// import styles from 'index.less';

const App:React.FC=()=>{
     const [quantityTotal,setQuantityTotal]=useState(0);
     const [boxTotal,setBoxTotal]=useState(0);
     const [tdata,setTdata]=useState<any[]>([]);   
     const [open,setOpen]=useState(false);                        

     const formRef_main=useRef<ProFormInstance>();
     const editableRef=useRef<EditableFormInstance>();
     const actionRef=useRef<ActionType>();
     const formRef_query=useRef<ProFormInstance>();

     const [openSale,setOpenSale]=useState(false);
     const formRef_sale=useRef<ProFormInstance>();
     const actionRef_sale=useRef<ActionType>();
     const [selectedRecord,setSelectedRecord]=useState<any[]>([]);
     const [selectedDetail,setSelectedDetail]=useState<any[]>([])
     const mtable_ref=useRef<ActionType>();

     const [openRecord,setOpenRecord]=useState(false);
      const editableRef2=useRef<EditableFormInstance>();
     const actionRef2=useRef<ActionType>();
     const formRef_record=useRef<ProFormInstance>();
     const [tdata2,setTdata2]=useState<any[]>([]);
     
     const [materialOption,setMaterialOption]=useState([]);
     const [etype,setEtype]=useState(1);

    const [selectedLineKeys,setSelectedLineKeys]=useState<any[]>([]);

     useEffect(()=>{
       //每间隔30秒保存一次数据，自动任务
        let autoboxing=setInterval(()=>{
        if(etype==0&&tdata.length>0){
         // alert('自动保存数据');   
            saveBoxing();
         }else
            clearInterval(autoboxing);
        },1000*30);
        //退出时清除自动任务
        return ()=>{
            clearInterval(autoboxing);
        };
     },[etype,tdata]);


    interface DataType{
        mid?:number,id?:number,x_id?:number,org_id?:number,custom_id?:number,operate_time?:string,
        operater_id?:number,saletype_id?:number,code?:string,state?:number,status?:number,
        memo?:string,source_type?:string,source_id?:number,addition?:string,business_id?:number,
        material_id?:number,userdefine_id?:string,userdefine_name?:string,quantity?:number,taxrate?:number,
        total?:number,netprice?:number,nettotal?:number,source_type2?:string,source_id2?:number,
        state2?:number,status2?:number,memo2?:string,deliverdate2?:string,material_addition?:string,
        material_code?:string,material_name?:string,scode?:string,invstd?:string,invstd2?:string,
        brand?:string,munit_name?:string,custom_name?:string,org_name?:string,operater_name?:string,
        business_name?:string,saletype_name?:string,zx_user_id?:number,
    }

    

    const columns1:ProColumns<DataType>[]=[
        {dataIndex:'id',title:'ID'},
        {dataIndex:'org_name',title:'部门'},
        {dataIndex:'custom_name',title:'店铺'},
        {dataIndex:'business_name',title:'业务员'},
        {dataIndex:'code',title:'单据编码'},
        // {dataIndex:'deliverdate',title:'交货日期'},
        {dataIndex:'memo',title:'销售拣货备注'},{dataIndex:'operater_name',title:'录入人'},
        {dataIndex:'operate_time',title:'录入时间',valueType:'date'},
        {dataIndex:'source_type',title:'销售拣货来源'},
        // {dataIndex:'state',title:'进度',
        //   render:(text:any)=>state2text(1,text),
        // },
        {dataIndex:'status',title:'状态',
          render:(text:any)=>status2text(text)
        },
    ];

    interface DataType2{
        rid?:number,id:number,material_id?:number,material_code?:string,material_name?:string,
        invstd?:string,invstd2?:string,userdefine_id?:string,userdefine_name?:string,munit_name?:string,
        quantity?:number,taxrate?:number,total?:number,netprice?:number,nettotal?:number,price:number,
        deliverdate2?:string,state2?:number,status2?:number,memo2?:string,material_addition?:string,
        pic?:string,fncode?:string,
    }

    const columns2:ProColumns<DataType2>[]=[
        {dataIndex:'rid',title:'RID',editable:false,hidden:true,},
        {dataIndex:'id',title:'ID',editable:false,hidden:true,},
        {dataIndex:'material_id',title:'物料ID',editable:false,hidden:true,},
        {dataIndex:'pic',title:'图片' ,editable:false,
         //   render:(text)=>{
         //       var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
         //       return <Image src={pic}  
         //              style={{width:100,height:100}} alt='无' />
         //  },
          render:(text,record,index,k)=>{
                            var pic="/basis_api/file/get2?filename="+record.material_code;
                            return   <Image src={pic}  style={{width:50,height:50}} alt='无' />
           }},
        {dataIndex:'material_code',title:'SKU码',editable:false,valueType:'text',},
        {dataIndex:'fncode',title:'FN码',editable:false,},
        {dataIndex:'material_name',title:'名称',editable:false,},
        {dataIndex:'invstd',title:'包装包装规格',editable:false,},
        {dataIndex:'invstd2',title:'型号',editable:false,},
        {dataIndex:'userdefine_id',title:'自定义ID',editable:false,hidden:true,},
        {dataIndex:'userdefine_name',title:'自定义值',editable:false,},
      //   {title:'属性',editable:false,
      //       render:(text,record)=><QueryUserDefine setData={setUserDefine} 
      //                     objtype={1} dotype={1} id={record.material_id} setRowno={setRowno} rowno={record.rid} />
      //      },
        {dataIndex:'munit_name',title:'计量单位',editable:false,},
        {dataIndex:'quantity',title:'数量',valueType:'digit',},
        {dataIndex:'deliverdate',title:'需求日期',valueType:'date',width:200},
        {dataIndex:'state2',title:'进度',editable:false,hidden:true},
        {dataIndex:'status2',title:'状态',editable:false,hidden:true,},
        {dataIndex:'memo',title:'备注',ellipsis:true,width:200},
      //   {dataIndex:'material_addition',title:'物料附件',editable:false,hidden:true,},
     ];

    
   //   const [columns,setColumns]=useState<ProColumns[]>([
   //            {dataIndex:'sku',title:'SKU',width:'8%',
   //                onCell:(record:any, index:any, text:any)=>{
   //                   if(index==0)
   //                        return {style:{color:'red',fontSize:20}};
   //                    else
   //                        return {style:{color:'red',fontSize:20}};
   //                 }},
   //            {dataIndex:'fncode',title:'FNCODE',width:'8%',
   //                onCell:()=>{return {style:{color:'red',fontSize:20}};}
   //             }]);
   const [columns,setColumns]=useState<ProColumns[]>([
      {dataIndex:'material_code',title:'SKU',width:'8%',editable:false,valueType:'text',
                  onCell:(record:any, index:any, text:any)=>{
                     if(index==0)
                          return {style:{color:'red',fontSize:20}};
                      else
                          return {style:{color:'red',fontSize:20}};
                   }},
              {dataIndex:'fncode',title:'FNCODE',width:'8%',editable:false,
                  onCell:()=>{return {style:{color:'red',fontSize:20}};}
               },
               {dataIndex:'material_id',title:'mid',hidden:true ,editable:false,},
               {dataIndex:'id',title:'id',hidden:true ,editable:false,},
               {dataIndex:'quantity',title:'应发货数',width:'5%',editable:false,},
               {dataIndex:'quantity_done',title:'已装箱数',width:'5%',editable:false,},
               {dataIndex:'quantity_diff',title:'缺料数',width:'5%',editable:false,
                                 onCell:(record:any,index:any,text:any)=>{
                                    return {
                                       style:{color:'red',fontSize:20}
                                    }
                                 },
                } ]);


   //保存装箱记录----------------------------------------------
    async function saveBoxing(){
       if(tdata.length==0||formRef_main.current?.getFieldValue('quantity_total')==undefined
              ||formRef_main.current?.getFieldValue('box_total')==undefined){
                  //  alert(tdata.length);
                   message.warning('没有装箱数据，不能保存');
              }
       else{
         // alert(JSON.stringify(tdata));
         var fdata=formRef_main.current?.getFieldsValue();
         fdata={...fdata,
               status:fdata.btype,
               deliverdate:moment(moment(fdata.deliverdate).toDate()).format('YYYY-MM-DD HH:mm:ss')};
            // alert(JSON.stringify(fdata));
         var ntdata=new Array();
         // alert(JSON.stringify(tdata));
         if(tdata.length>0){
            var tkeys=Object.keys(tdata[0]);
            tdata.map((item:any)=>{
               if(item.material_id!=0)
                  tkeys.forEach((it)=>{
                     var obj:any=new Object();
                     // obj['sku']=item.sku;
                     obj['material_id']=item.material_id;
                     obj['source_did']=item.source_did;
                     if(item.material_code!='汇总'&&it!='material_code'&&it!='fncode'&&it!='quantity_done'
                        &&it!='quantity_diff'&&it!='source_did'&&it!=''&&item[it]){
                          obj['box_sno']=it;
                          obj['quantity']=item[it];
                          ntdata.push(obj);
                     };
                 });
            }); 
         };

         // source,x_id,operater_id,etype,fdata
         ntdata=ntdata.filter(item=>item.material_id!=null);
         const x=await s_produce_updateInfo({source:'boxing',x_id:1,operater_id:1,
                         fdata:{fdata,tdata:ntdata}});
                         
         if(x.success){
            // alert(x.data[0][0].mid);
            formRef_main.current?.setFieldsValue({etype:0,
                                                  btype:0,
                                                  id:x.data[0][0].mid,
                                                  vouch_code:x.data[0][0].vouch_code
                                                });
            
            message.success('保存成功');
            setEtype(0);
            }
         else
            message.error('失败，请联系管理员');
        };
     };

     //查询历史装箱记录，进行修改或补箱----------------------------
     async function queryBoxing(){
         // setEtype(0);
         setOpen(true);
     };

     //执行查询
     async function query(){
        setEtype(0);
        var  fdata=formRef_query.current?.getFieldsValue();
        fdata={...fdata,
               begindate:(fdata.begindate==undefined||fdata.begindate==null)?null
                          :moment(moment(fdata.begindate).toDate()).format('YYYY-MM-DD'),
               enddate:(fdata.enddate==undefined||fdata.enddate==null)?null
                          :moment(moment(fdata.enddate).toDate()).format('YYYY-MM-DD'),
              }; 

      //   alert(JSON.stringify(fdata));
      //  x_id,cate_id,id,source,fdata
       const x:any=await s_getcommontableinfo({x_id:1,cate_id:[],id:0,source:'boxing',fdata});
       if(x.success){
            // alert(JSON.stringify(x.data[0]));
            if(x.data[0]&&x.data[0].length>0){
                  //  动态创建表结构
                    var newcol:ProColumns[]=[{ dataIndex:'material_code',title:'SKU',width:'8%',editable:false,
                     onCell:(record:any, index:any, text:any)=>{
                        if(index==0)
                             return {style:{color:'red',fontSize:20}};
                         else
                             return {style:{color:'red',fontSize:20}};
                      }},
                      {dataIndex:'fncode',title:'FNCODE',width:'8%',editable:false,
                          onCell:()=>{return {style:{color:'red',fontSize:20}};}
                    }];
                  //   alert(JSON.stringify(x.data[2][0].temp));
                    var temp=JSON.parse(x.data[2][0].temp);               
                    temp&&temp.map((item:any)=>{
                       newcol.push({dataIndex:item,title:item,width:50,
                        onCell:(record:any, index:any, text:any)=>(index==0?{style:{color:'red',fontSize:20}}:{})});
                    });
                  //   设置列
                    setColumns(newcol);
                  //   设置表头汇总
                    formRef_main.current?.setFieldsValue({ ...x.data[0][0]});
                    setBoxTotal(x.data[0][0].box_total);
                    setQuantityTotal(x.data[0][0].quantity_total);

                  //   alert(JSON.stringify(x.data[1]));
                    //设置表体明细--先添加汇总行
                    //按箱号（列名）计算汇总数量-------
                    var f=x.data[1];
                    var keys:any[]=[];
                    newcol.map((item3:any)=>{
                        keys.push(item3.dataIndex);
                    });
                    var newobj:any=new Object();
                    newobj['material_code']='汇总';
                    newobj['fncode']='';
                    f.map((item:any)=>{
                        keys.forEach((key)=>{
                              if(key!='material_code'&&key!='fncode')
                                  newobj[key]=(newobj[key]?newobj[key]:0)+(item[key]?item[key]:0);
                           });
                    });

                    setTdata([newobj,...f]);
                  //   setTdata(x.data[1]);
                   message.success('查询成功');
                   formRef_main.current?.setFieldValue('btype',0);
             };
       }else
          message.warning('没有找到装箱数据');
        
     };

   //   装箱生成销售出库单-------
   async function stockOutBoxing(){
       if(tdata.length==0)
            message.warning('没有装箱数据，不能出库');
      //  else if(formRef_main.current?.getFieldValue('status')==2)
      //      message.warning('装箱单已出库，请先删除出库单，再重新出库。');
       else if(formRef_main.current?.getFieldValue('custom_id')==undefined
               ||formRef_main.current?.getFieldValue('warehouse_id'==undefined))
          message.warning('店铺和仓库都不能为空');
       else{
          var fdata=formRef_main.current?.getFieldsValue();
          fdata={...fdata,org_id:1,outtype_id:7};
          var ntdata:any=[];
          var tkeys=Object.keys(tdata[0]);
          tdata.map((item:any)=>{
               tkeys.forEach((it)=>{
                  var obj:any=new Object();
                   // obj['sku']=item.sku;
                   obj['material_id']=item.material_id;
                   obj['source_did']=item.source_did;
                   if(item.material_code!='汇总'&&it!='material_code'&&it!='fncode'&&it!='quantity_done'
                        &&it!='quantity_diff'&&it!='source_did'&&it!=''&&item[it]){
                        obj['box_sno']=it;
                        obj['quantity']=item[it];
                        ntdata.push(obj);
                   };
               });
          }); 


          //调用出库函数
         //  x_id,operater_id,etype,source,JSON.stringify(tdata)
          const x=await s_stockOut({x_id:1,operater_id:1,etype:formRef_main.current?.getFieldValue('btype'),
                         source:'boxing',tdata:{fdata,tdata:ntdata}});
          if(x.success){
            message.success('出库成功');
            formRef_main.current?.setFieldValue('btype',2);
          }else
            message.error('保存失败，请联系管理员');

       };
   };

   //导入发货单
     function querySale(){
         setOpenSale(true);
     };

     //执行查询发货单
     async function doQuerySale(){
       const vouch_code=formRef_sale.current?.getFieldValue('vouch_code');
          const org_id=formRef_sale.current?.getFieldValue('org_id');
          const custom_id=formRef_sale.current?.getFieldValue('custom_id');
          const business_id=formRef_sale.current?.getFieldValue('business_id');
          var begindate=formRef_sale.current?.getFieldValue('begindate');
          if(begindate)
              begindate=moment(moment(begindate).toDate()).format('YYYY-MM-DD');
         var enddate=formRef_sale.current?.getFieldValue('enddate');
          if(enddate)
              enddate=moment(moment(enddate).toDate()).format('YYYY-MM-DD');
       
          const x=await s_getStockInfo({source:'v_sale_order_main2',x_id:1,
                               fdata:{x_id:1,vouch_code,org_id,custom_id,business_id,begindate,enddate}});
       
          if(x.data[0].length==0)
             message.warning('没有找到对应的数据');
           else{
              formRef_sale.current?.setFieldsValue({                                         
                                             editable_sale:x.data[0],
                                             // person_id:x.data[0][0].zx_user_id,
                                         });
           };
     };

     //开始装箱，带入装箱SKU和数量到装箱界面
     function beginBoxing(){
         if(selectedRecord.length==0)
            message.warning('请选择要装箱的FBA发货单');
         else{
         // selectedDetail:存放着发货明细，将发货明细值带入到装箱表中，注意要带id,material_id隐藏列
         var newcolumn:any[]=[
              {dataIndex:'material_code',title:'SKU',width:'8%',editable:false,valueType:'text',
                  onCell:(record:any, index:any, text:any)=>{
                     if(index==0)
                          return {style:{color:'red',fontSize:20}};
                      else
                          return {style:{color:'red',fontSize:20}};
                   }},
               {dataIndex:'fncode',title:'FNCODE',width:'8%',editable:false,
                  onCell:()=>{return {style:{color:'red',fontSize:20}};}
               },
               {dataIndex:'material_id',title:'mid', hidden:true,editable:false, },
               {dataIndex:'source_did',title:'id',hidden:true,editable:false,  },
               
               {dataIndex:'quantity',title:'应发货数',width:'5%',editable:false,},
               {dataIndex:'quantity_done',title:'已装箱数',width:'5%',editable:false,},
               {dataIndex:'quantity_diff',title:'缺料数',width:'5%',editable:false,
                                 onCell:(record:any,index:any,text:any)=>{
                                    return {
                                       style:{color:'red',fontSize:20}
                                    }
                                 },
                }                 
            ];
 
          //填写上述明细数据到表格中---注意：在导入时，要保存原有数据---过滤物料ID ----2025-06-28----
      var td:any[]=[];    
      if(selectedDetail.length>0)   
          td=selectedDetail.map((item:any)=>({
             material_id:item.material_id,
             fncode:item.fncode,
             source_did:item.id,
             quantity:item.quantity,
             quantity_done:0,
             quantity_diff:item.quantity,
             material_code:item.material_code,
          }));
  
         

          //把现有的数据提取出来，过滤掉已有的ID
         //  var etable=formRef_main.current?.getFieldValue('editable');
         //      etable=etable?etable:[];

         //  alert(JSON.stringify(tdata));
           //当主表为空时，导入发货单即为新增，生成新列；否则沿用原有的列
          if(tdata.length==0)
              setColumns(newcolumn);
          //将原tdata的重量长拆出，附加到表后

           var td2=[];
           var td3=[{material_id:0,material_code:'重量（KG）',fncode:''},
            {material_id:0,material_code:'长度（CM）',fncode:''},
            {material_id:0,material_code:'宽度（CM）',fncode:''},
            {material_id:0,material_code:'高度（CM）',fncode:''},
           ];

           if(tdata.length>0){
              td2=tdata.filter(item=>item.material_code!='重量（KG）'
                                &&item.material_code!='长度（CM）'
                                &&item.material_code!='宽度（CM）'
                                &&item.material_code!='高度（CM）');
             td3=tdata.filter(item=>item.material_code=='重量（KG）'
                                ||item.material_code=='长度（CM）'
                                ||item.material_code=='宽度（CM）'
                                ||item.material_code=='高度（CM）');
            };

           td.map((item:any)=>{
                 var temp=tdata.filter((item2:any)=>item2.material_id==item.material_id);
                 if(temp==undefined||temp.length==0)
                      td2.push(item);
          }) ;
 
         //  setTdata(td);
          setTdata([...td2,...td3]); 
         // formRef_main.current?.setFieldValue('editable',etable);
      
          setOpenSale(false);
         //  formRef_main.current?.setFieldValue('vouch_code',selectedRecord[0].code);

         //  formRef_main.current?.resetFields();

            var fhd_code=formRef_main.current?.getFieldValue('fhd_code');
          if(fhd_code==undefined||fhd_code=='')
               formRef_main.current?.setFieldsValue({
                                                  fhd_code:selectedRecord[0].code,
                                                  custom_id:selectedRecord[0].custom_id,
                                                  zx_user_id:selectedRecord[0].zx_user_id,
                                                  db_user_id:selectedRecord[0].db_user_id,
                                                  jh_user_id:selectedRecord[0].jh_user_id,
                                                //   whposition_id:selectedRecord[0].whposition_id,
                                                });
     };
   };

//临时添加新SKU到装箱单中------------------------------
async function addMaterial(){
   // var fdata=formRef_main.current?.getFieldValue('editable_main');
   if(tdata==undefined||tdata.length==0)
      message.warning('请先导入发货单');
   else{
      var id=formRef_main.current?.getFieldValue('add_material');
      const x=await s_getTableInfo({x_id:1,source:'v_material',id});
      // alert(JSON.stringify(x.data[0]));
      const y=x.data[0];
      var flag=tdata.filter(item=>item.material_code==y.code);
      // alert(JSON.stringify(flag));

      if(flag==undefined||flag.length==0){
      //拆分重量长度，再插入
          var td2=[];
           var td3=[];
           if(tdata.length>0){
              td2=tdata.filter(item=>item.material_code!='重量（KG）'
                                &&item.material_code!='长度（CM）'
                                &&item.material_code!='宽度（CM）'
                                &&item.material_code!='高度（CM）');
              td3=tdata.filter(item=>item.material_code=='重量（KG）'
                                ||item.material_code=='长度（CM）'
                                ||item.material_code=='宽度（CM）'
                                ||item.material_code=='高度（CM）');
            };

         //   td.map((item:any)=>{
         //         var temp=tdata.filter((item2:any)=>item2.material_id==item.material_id);
         //         if(temp==undefined||temp.length==0)
         //              td2.push(item);
         //  }) ;

      setTdata([...td2,{material_id:y.id,material_code:y.code,fncode:y.fn_sku,
         quantity:0,quantity_done:0,quantity_diff:0},...td3]);
 
     }else
         message.warning('商品SKU重复，不能加入');
   };
};

//装箱称重
function recordBoxing(){
   //   const x=editableRef.current?.getRowsData?.();
   if(tdata.length==0)
      message.warning('没有要装箱的商品，不能称重');
   else{
      const x=tdata;
      var x0=x&&x.filter((item:any)=>item.material_code=='重量（KG）'||item.material_code=='宽度（CM）'
                      ||item.material_code=='长度（CM）'||item.material_code=='高度（CM）');
      //  alert(JSON.stringify(x));                  
      //  alert(JSON.stringify(x0));
      if(x0==undefined||x0?.length==0) 
         x0=[{material_code:'重量（KG）',2:0,1:0},{material_code:'宽度（CM）',}
           ,{material_code:'长度（CM）',},{material_code:'高度（CM）',},];
    
      //   alert(JSON.stringify(x0));
      // formRef_record.current?.setFieldValue('editable2',x0);
      //装箱称重初始化值
       setTdata2(x0);
       setOpenRecord(true);
      };
  };


function doRecord(){
    const x=editableRef2.current?.getRowsData?.();
       x?.map((item:any)=>{
          actionRef2.current?.startEditable?.(item.material_code);
         // alert(item.material_code);
      });
};

async function saveRecord(){
    var x=editableRef2.current?.getRowsData?.();
    x=x?x:[];
   //  alert(JSON.stringify(x));
   //  var x0=editableRef.current?.getRowsData?.();
   //  x0=x0?x0:[];
   //  alert(JSON.stringify([...tdata,...x]));
   //  formRef_main.current?.setFieldValue('editable',[...x0,...x]);
   var y=tdata.filter((item:any)=>item.material_code!='重量（KG）'&&item.material_code!='宽度（CM）'
                                  &&item.material_code!='长度（CM）'&&item.material_code!='高度（CM）');
   // alert(JSON.stringify(y));                               
   
   //保存到装箱称重表中
    if(formRef_main.current?.getFieldValue('vouch_code')==undefined||formRef_main.current?.getFieldValue('vouch_code')=='')
              message.warning('装箱数据未保存，不能保存重量。请先保存装箱表');
    else{
         var ntdata=new Array();
         // alert(JSON.stringify(tdata));
         if(tdata.length>0){
            var tkeys=Object.keys(tdata[0]);
            x.map((item:any)=>{
                 tkeys.forEach((it:any)=>{
                    var obj:any=new Object();
                     // obj['sku']=item.sku;
                     obj['material_code']=item.material_code.indexOf('重')==0?'weight'
                                          :item.material_code.indexOf('长')==0?"long"
                                          :item.material_code.indexOf('宽')==0?'wide'
                                          :'height';
                     // obj['source_did']=item.source_did;
                     if(item.material_code!='汇总'&&it!='material_code'&&it!='fncode'&&it!='quantity_done'
                        &&it!='quantity_diff'&&it!='source_did'&&it!=''&&item[it]){
                          obj['box_sno']=it;
                          obj['quantity']=item[it];
                          ntdata.push(obj);
                     };
                 });
            }); 
         };
         //  alert(JSON.stringify(fdata));
         //  alert(JSON.stringify(ntdata));
         // source,x_id,operater_id,etype,fdata
         const x2=await s_produce_updateInfo({source:'boxing_weight',x_id:1,operater_id:1,
                         fdata:{vouch_code:formRef_main.current?.getFieldValue('vouch_code'),
                                tdata:ntdata}});
                         
         if(x2.success){
            // alert(x.data[0][0].mid);
            // formRef_main.current?.setFieldsValue({etype:0,
            //                                       id:x.data[0][0].mid,
            //                                       vouch_code:x.data[0][0].vouch_code
            //                                     });
            message.success('装箱称重保存成功');
            message.success('保存成功');
            //更新界面
            setTdata([...y,...x]);
            }
         else
            message.error('失败，请联系管理员');
        };
};

//导出EXCEL文件------------------------------2025-7-03--------------------
function downloadExcel(){
  if(tdata.length==0)
    message.warning('没有要导出的数据');
  else{
     const ExcelJS=require('exceljs');
     const workbook = new ExcelJS.Workbook();
     const ws=workbook.addWorksheet('装箱单');
     //EXCEL标题
      const headerStyle = {
            font: {
                name: 'Arial',
                family: 4,
                size: 12,
                bold: true,
                // color: { argb: 'FF0000' }
            },
            fill: {
                type: 'pattern',
                pattern: 'solid',
                // fgColor: { argb: 'FFFF00' },
                // bgColor: { argb: 'FFFF00' }
            },
            alignment: {
                vertical: 'middle',
                horizontal: 'center'
            },
            border: {
                top: {style: 'thin', color: {argb: '000000'}},
                left: {style: 'thin', color: {argb: '000000'}},
                bottom: {style: 'thin', color: {argb: '000000'}},
                right: {style: 'thin', color: {argb: '000000'}}
            }
        };
        //设置标题
       var headTitle=['material_code','fncode'];
      //  var keys:any[]=[];
           columns.map((item3:any)=>{
              if( item3.dataIndex!='fncode'&&item3.dataIndex!='material_code')  
                  headTitle.push(item3.dataIndex);
            });

      //  alert(JSON.stringify(headTitle));
      //  alert(JSON.stringify(columns));
       ws.addRow(headTitle);
      //  .eachCell((cell:any) => {
      //           cell.style = headerStyle
      //       });

       tdata.forEach(it=>{
            var obj:any=[];
            headTitle.map((item:any)=>{
               // alert(item+':'+it[item]);
               obj.push(it[item]);
            });
            ws.addRow(obj);
        });

      //   alert(JSON.stringify(tdata));
        workbook.xlsx.writeBuffer()
            .then((buffer:any) => {
                // 创建 Blob 对象
                const blob = new Blob([buffer], 
                  {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});

                // 创建下载链接
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `装箱单`+formRef_main.current?.getFieldValue('vouch_code')+`.xlsx`;
                a.click();

                // 清理 URL
                setTimeout(() => {
                    window.URL.revokeObjectURL(url);
                    a.remove();
                }, 100);
            })
            .catch((err:any) => console.error('Error creating file:', err));
          };
};

   //=============================================================================================================
     return <>
    <ProCard style={{height:760,overflow:'auto'}}>
    <ProForm submitter={false} labelAlign='left' labelCol={{offset:0,span:7}} layout="horizontal"
        style={{fontSize:50}} formRef={formRef_main}
        initialValues={{btype:etype}}
    >
       <Row gutter={8}>
         <Col span={4}>
           <Space.Compact>
               <Button style={{fontSize:30,height:50}}>箱码</Button>
               <ProFormDigit name='box'   width={80}  
                 fieldProps={{
                      style:{fontSize:30,height:50} ,
                      onBlur:(value:any)=>{
                     //  onKeyDown:(e:any)=>{
                        // alert(JSON.stringify(e));
                        if(value>0){
                           // var v=e.target.value;
                           var t=columns.filter((item:any)=>item.dataIndex==value); 
                           // alert(t.length);
                           if(t&&t.length==0){
                              //总箱数递增
                              setBoxTotal(boxTotal+1);
                              formRef_main.current?.setFieldValue('box_total',boxTotal+1);
                              //界面动态添加列
                              setColumns([...columns,{dataIndex:value,title:value,width:50,
                                 onCell:(record:any, index:any, text:any)=>(index==0?{style:{color:'red',fontSize:20}}:{})}]);
                           };
                        };
                     }, 
                   }} 
                 />
           </Space.Compact>
         </Col>
         <Col span={4}>
             <Space.Compact>
                <Button style={{fontSize:30,height:50}}>数量</Button>
                <ProFormDigit name='quantity' width={80} min={-100}
                   fieldProps={{
                          style:{fontSize:30,height:50},
                          
                    }}  />
           </Space.Compact>
         </Col>
         <Col span={5}>
             <Space.Compact>
                  <Button style={{height:50,fontSize:30,color:'red'}}>SKU扫码</Button>  
                  <ProFormText name='qrcode'   width={200}  
                       fieldProps={{
                            style:{fontSize:30, height:50}, 
                            onKeyDown:(e:any)=>{
                               if(e.key=='Enter'&&e.target.value!=undefined){
                                 var vin=e.target.value;
                                 // 扫入的码包含三部分：id_code_fncode，需拆解
                                 var p1=vin.indexOf('_');
                                 var material_id=vin.substring(0,p1);
                                 // alert(p1);
                                 var sku=vin.substring(p1+1,vin.indexOf('_',p1+1));
                                 // alert(vin.indexOf('_',p1+1))
                                 var fncode=vin.substring(vin.indexOf('_',vin.indexOf('_',p1+1))+1);
                                 // alert(vin.indexOf('_',vin.indexOf('_',p1+1)));

                                 // alert(material_id+'+'+sku+'+'+fncode);

                                 var box=formRef_main.current?.getFieldValue('box');
                                 var quantity=formRef_main.current?.getFieldValue('quantity');
                                 var newdata:any[]=[];
                                 if(box==undefined||quantity==undefined)
                                    message.warning('箱号和数量，必须填写');
                                 else if(tdata.length==0)
                                    message.warning('请先导入发货单');
                                 else
                                 {
                                    // var f=formRef_main.current?.getFieldValue('editable');
                                    // var f=editableRef.current?.getRowsData?.();
                                    // var f=tdata.length>0?tdata.filter((_,index)=>index>0):[];
                                    var f=tdata.length>0?tdata.filter((item:any)=>item.material_code!='汇总'
                                            &&item.material_code!='重量（KG）'&&item.material_code!='宽度（CM）'
                                            &&item.material_code!='长度（CM）'&&item.material_code!='高度（CM）'):[];
                                    // alert(JSON.stringify(f));
                                    //  alert('f---------'+JSON.stringify(f));
                                    var t=(f&&f.filter((item:any)=>item.material_id==material_id));
                                    
                                    if(t==undefined||t.length==0)
                                       message.warning('此发货单未包含此物料');
                                    else{
                                        f=f.map((item:any)=>{
                                           if(item.material_id==material_id){
                                              item[box]=quantity+(item[box]?item[box]:0);
                                             //   alert(JSON.stringify(item));
                                             //按行求已装箱数
                                               item.quantity_done=item.quantity_done+quantity;
                                               item.quantity_diff=item.quantity_diff-quantity;
                                               return item;
                                           }else
                                               return item;
                                        });
                                       
                                       //  actionRef2.current?.reload?.();
                                        newdata=f;
                                      
                                    //按箱号（列名）计算汇总数量-------
                                        var keys:any[]=[];
                                        columns.map((item3:any)=>{
                                          keys.push(item3.dataIndex);
                                        });
                                        var newobj:any=new Object();
                                        newobj['material_code']='汇总';
                                        newobj['fncode']='';
                                       //  alert(JSON.stringify(keys));
                                        f.map((item:any)=>{
                                            keys.forEach((key)=>{
                                                  if(key!='material_code'&&key!='fncode'&&key!='material_id'
                                                      &&key!='quantity'
                                                       &&key!='quantity_done'&&key!='quantity_diff'&&key!='id')
                                                      newobj[key]=(newobj[key]?newobj[key]:0)+(item[key]?item[key]:0);
                                               });
                                        });
                                        
                                        //附加称重数据
                                        var td2=tdata.filter((item:any)=>
                                            item.material_code=='重量（KG）'||item.material_code=='宽度（CM）'
                                            ||item.material_code=='长度（CM）'||item.material_code=='高度（CM）');

                                        setTdata([newobj,...newdata,...td2]);

                                        actionRef.current?.reload?.();
                                        //自动累计表头总数量
                                        setQuantityTotal(quantityTotal+quantity);
                                        formRef_main.current?.setFieldValue('quantity_total',quantityTotal+quantity);
                                        formRef_main.current?.setFieldValue('qrcode',null);
                                       //  formRef_main.current?.setFieldValue('vouch_code',selectedRecord[0].vouch_code);
                                 };
                                 };
                            };
                          },
                }} />  
               </Space.Compact>
         </Col>
         <Col span={2}>
              <ProFormRadio.Group name='btype' label='状态' disabled
              options={[{value:0,label:'编辑'},
              {value:1,label:'新增'},
            //   {value:2,label:'已出库'}
            ]} 
              />
         </Col>
         {/* <Col span={2}>
              <ProFormRadio.Group name='status' label='状态' 
              options={[{value:0,label:''},{value:1,label:'是'}]} />
         </Col> */}
         <Col span={7}>
           <Space>
             <Button style={{width:160,height:50,fontSize:20}} onClick={()=>querySale()}>导入发货单</Button>
             <Button style={{width:120,height:50,fontSize:20}} onClick={()=>saveBoxing()}>保存</Button> 
             {/* <Button style={{width:120,height:50,fontSize:20}} onClick={()=>stockOutBoxing()}>出库</Button> */}
             <Button style={{width:120,height:50,fontSize:20}} onClick={()=>recordBoxing()}>装箱称重</Button>
             <Button style={{width:120,height:50,fontSize:20}} onClick={()=>queryBoxing()}>查询装箱单</Button>
             <Button onClick={()=>downloadExcel()}>导出EXCEL</Button>
             {/* <Button style={{width:80,height:50,fontSize:20}} onClick={()=>queryBoxing()}>打包</Button> */}
             {/* <Button style={{width:80,height:50,fontSize:20}} onClick={()=>addMaterial()}>+SKU</Button> */}
           </Space>
         </Col>
        
        
       </Row>
       <Row gutter={8}>
        <Col span={4}>
        <ProFormText name='fhd_code' label='发货单号' width={200} />
        <ProFormText name='vouch_code' label='装箱单号' width={200} />
        {/* <ProFormSelect name='db_user_id' label='打包人'    width={200} 
                        showSearch
                        request={async ()=>{
                              const x=await s_getSelectData({x_id:1,source:'base_person'});
                              return x.data;}}
          /> */}
        <ProFormText name='id' label='ID' width={200} />
        </Col>
        <Col span={4}>
        <ProFormSelect name='warehouse_id' label='出货仓库'    width={200} 
                     //  rules={[{required:true,message:'必填项'}]}
                        showSearch
                        request={async ()=>{
                              const x=await s_getSelectData({x_id:1,source:'base2_ware'});
                              return x.data;}}
          />
         <ProFormSelect name='custom_id' label='店铺'    width={200} 
                        rules={[{required:true,message:'必填项'}]}
                        showSearch
                        request={async ()=>{
                              const x=await s_getSelectData({x_id:1,source:'v_custom'});
                              return x.data;}}
                    />
         <ProFormSelect name='zx_user_id' label='装箱人'    width={200} 
                        showSearch
                        request={async ()=>{
                              const x=await s_getSelectData({x_id:1,source:'base_person'});
                              return x.data;}}
          />
        </Col>
        <Col span={3}>
           <ProFormText name='quantity_total' label='已装数量'  width={120}/>
           <ProFormText name='box_total' label='已装箱数'   width={120}/>
           <ProFormSelect name='jh_user_id' label='拣货人'    width={200} 
                        showSearch
                        request={async ()=>{
                              const x=await s_getSelectData({x_id:1,source:'base_person'});
                              return x.data;}}
          />
        </Col>
        <Col span={4}>
           <ProFormDatePicker name='deliverdate' label='发货日期' initialValue='2025-03-26' width={200}/>
            <ProFormSelect name='whposition_id' label='拣货暂存位'    width={200} 
                        showSearch
                        request={async ()=>{
                              const x=await s_getSelectData({x_id:1,source:'jh_whposition'});
                              return x.data;}}
          />
             
        </Col>
        <Col span={3}>
             {/* <ProFormSelect name='person_id' label='打包人'    width={120} 
                        showSearch
                        request={async ()=>{
                              const x=await s_getSelectData({x_id:1,source:'base_person'});
                              return x.data;}}
             /> */}
             
           <Space.Compact>
               <ProFormSelect name='add_material' width={200}
                  showSearch
                  options={materialOption}
                  //  request={async ()=>{
                  //             const x=await s_getSelectData({x_id:1,source:'v_material'});
                  //             return x.data;}}
                  
                  fieldProps={{
                    async  onSearch(value){
                        const x=await s_getSelectData({x_id:1,source:'material_'+value});
                        // return x.data;
                        setMaterialOption(x.data);
                        // alert(JSON.stringify(x.data));
                     },
                  }}
               />
               <Button onClick={()=>addMaterial()}>+SKU</Button> 
            </Space.Compact>

             <ProFormText name='memo' label='备注'   width={300}/>
        </Col>
       
             
       
       </Row>

         <ProTable 
             name='editable'
             rowKey='sku'
             actionRef={actionRef}
            //  editableFormRef={editableRef}
             search={false}
             options={false}
             columns={columns}
             dataSource={tdata}
             bordered
             columnEmptyText={false}
             
            //  recordCreatorProps={false}
            //  editable={{
            //      type:'multiple',
            //  }}
            // scroll={{x:'auto'}}  
       />
        
      </ProForm>

      {/* 查询历史装箱记录，并可以进行修改---------------------------------------------------------- */}
       <Modal open={open} destroyOnClose onCancel={()=>setOpen(false)} onClose={()=>setOpen(false)}
           okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}} width={600}>
            <ProCard title='查询装箱单' style={{height:400}}
                extra={<Space>
                    <Button onClick={()=>query()}>开始查询</Button>
                     <Button onClick={()=>setOpen(false)}>关闭</Button>
                </Space>}
            >
               <ProForm submitter={false} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:5}}
                   formRef={formRef_query}
               >
                    <ProFormText name='vouch_code' label='装箱单号'  width={300}/>
                    <ProFormSelect name='custom_id' label='店铺'    width={300} 
                        showSearch
                        request={async ()=>{
                              const x=await s_getSelectData({x_id:1,source:'v_custom'});
                              return x.data;}}
                    />
                    <ProFormDatePicker name='begindate' label='装箱起始日期' />
                    <ProFormDatePicker name='enddate' label='装箱结束日期' />
               </ProForm>
            </ProCard>
      </Modal>
      </ProCard> 
      
      {/* 查询来源备料单----------------------------2025-05-20---------------------------------------- */}
       <Modal open={openSale} destroyOnClose onCancel={()=>setOpenSale(false)} onClose={()=>setOpenSale(false)}
            okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}} width='90%' style={{top:20}}>
            <ProCard title='查询发货单' style={{height:1000}}
                extra={<Space>
                    <Button onClick={()=>doQuerySale()}>开始查询</Button>
                    <Button onClick={()=>beginBoxing()}>开始装箱</Button>
                    <Button onClick={()=>setOpenSale(false)}>关闭</Button>
                </Space>}
            >
               <ProForm submitter={false} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:5}}
                   formRef={formRef_sale}
               >
                  <Row gutter={8}>
                     <Col span={6}>
                         <ProFormText name='vouch_code' label='发货单号'  width={300}/>
                        <ProFormSelect name='custom_id' label='店铺'    width={300} 
                            showSearch
                            request={async ()=>{
                              const x=await s_getSelectData({x_id:1,source:'v_custom'});
                              return x.data;}}
                    />
                     </Col>
                      <Col span={6}>
                         <ProFormSelect name='business_id' label='业务员'    width={300} 
                            showSearch
                             request={async ()=>{
                              const x=await s_getSelectData({x_id:1,source:'v_businesser'});
                              return x.data;}}
                         />
                          <ProFormSelect name='org_id' label='部门'    width={300} 
                              showSearch
                              request={async ()=>{
                              const x=await s_getSelectData({x_id:1,source:'base_organization'});
                              return x.data;}}
                    />
                     </Col>
                      <Col span={6}>
                           <ProFormDatePicker name='begindate' label='发货起始日期' />
                           <ProFormDatePicker name='enddate' label='发货结束日期' />
                     </Col>
                  </Row>
                  <ProCard style={{height:400,overflow:'auto'}}>
                       <EditableProTable<DataType>
                                name='editable_sale'
                                rowKey='id'
                                actionRef={mtable_ref}
                                search={false}
                                columns={columns1}
                                scroll={{y:300 }}
                                options={false}
                                recordCreatorProps={false}
                              //   request={async ()=>{
                              //             // alert(11);
                              //             const x=await s_getTableInfo({source:'v_sale_order_main2',x_id:1,id:0});
                              //             // alert(JSON.stringify(x.data));
                              //             return {
                              //               data:x.data,
                              //               success:true,
                              //             }
                              //    }}
                               rowSelection={{
                                          type:'radio',
                                          selectedRowKeys:selectedLineKeys,
                                          async onChange(selectedRowKeys, selectedRows:any, info) {
                                              setSelectedRecord(selectedRows);
                                              setSelectedLineKeys(selectedRowKeys);
                                              if(selectedRows.length>0){
                                                   const id=selectedRows[0].id;
                                                   const x=await s_getTableInfoDetail({source:'v_sale_order_detail2',x_id:0,mid:id});
                                                   setSelectedDetail( x.data );
                                                  //  alert(JSON.stringify(x.data));
                                              };
                                          },
                                        }} 
                              onRow={(record)=>{
                                         return {
                                            onClick:async ()=>{
                                               const k=record.id;
                                               setSelectedRecord([record]);
                                               setSelectedLineKeys([k]);
                                               if(k&&k>0){
                                                   const id=k;
                                                   const x=await s_getTableInfoDetail({source:'v_sale_order_detail2',x_id:0,mid:id});
                                                   setSelectedDetail( x.data );
                                                  //  alert(JSON.stringify(x.data));
                                              };
                                            },
                                          }
                                       }}
                              />
                         </ProCard>
                         <ProCard style={{height:400,overflow:'auto'}}>        
                              <ProTable<DataType2>
                                options={false}
                                rowKey='id'
                                // actionRef={mtable_ref}
                                search={false}
                                columns={columns2}
                                scroll={{y:300 }}
                                dataSource={selectedDetail}
                              />
                              </ProCard>  
                   
               </ProForm>
            </ProCard>
      </Modal>


       <Modal open={openRecord} destroyOnClose onCancel={()=>setOpenRecord(false)} onClose={()=>setOpenRecord(false)}
           okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}} width='90%' style={{top:20}}>
            <ProCard title='装箱称重' style={{height:1000}}
                extra={<Space>
                    <Button onClick={()=>doRecord()}>录入</Button>
                    <Button onClick={()=>saveRecord()}>保存</Button>
                    <Button onClick={()=>setOpenRecord(false)}>关闭</Button>
                </Space>}
            >
               <ProForm submitter={false} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:5}}
                   formRef={formRef_record}
                   initialValues={{editable2:tdata2}}
                    
               >
                  {JSON.stringify(tdata2)}
                 <EditableProTable
                     name='editable2'
                     rowKey='material_code'
                     actionRef={actionRef2}
                     editableFormRef={editableRef2}
            //  editableFormRef={editableRef}
                     search={false}
                     options={false}
                     columns={columns}
                     // dataSource={tdata2}
                     bordered
                     columnEmptyText={false}
                     recordCreatorProps={false}
                     editable={{
                         type:'multiple',
                      }}
                   />
               </ProForm>
               </ProCard>
        </Modal>
    </>;
};

export default App;

 